#include "logindialog.h"
#include "ui_LoginDialog.h"
#include "sqloperator.h"
#include <QMessageBox>

LoginDialog::LoginDialog(SqlOperator *dbOperator, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog),
    m_dbOperator(dbOperator)
{
    ui->setupUi(this);
    setWindowTitle("员工管理系统 - 登录");
    // 设置窗口固定大小
    setFixedSize(400, 300);
    // 设置密码框显示星号
    ui->passwordLineEdit->setEchoMode(QLineEdit::Password);
    // 连接信号槽
    connect(ui->loginButton, &QPushButton::clicked, this, &LoginDialog::on_loginButton_clicked);
    connect(ui->exitButton, &QPushButton::clicked, this, &LoginDialog::on_exitButton_clicked);
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

QString LoginDialog::getUserRole() const
{
    return m_userRole;
}

QString LoginDialog::getEmployeeId() const
{
    return m_employeeId;
}

void LoginDialog::on_loginButton_clicked()
{
    QString username = ui->usernameLineEdit->text();
    QString password = ui->passwordLineEdit->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "用户名和密码不能为空");
        return;
    }

    if (validateUser(username, password)) {
        accept();
    } else {
        QMessageBox::warning(this, "登录失败", "用户名或密码不正确，请重试。");
        // 清空密码框
        ui->passwordLineEdit->clear();
        // 让用户名框获得焦点
        ui->usernameLineEdit->setFocus();
    }
}

void LoginDialog::on_exitButton_clicked()
{
    reject();
}

bool LoginDialog::validateUser(const QString &username, const QString &password)
{
    if (!m_dbOperator || !m_dbOperator->isOpen()) {
        QMessageBox::critical(this, "数据库错误", "数据库连接未打开");
        return false;
    }

    // 检查login表是否存在
    if (!m_dbOperator->isExistTable("login")) {
        QMessageBox::critical(this, "数据库错误", "login表不存在");
        return false;
    }

    QList<QString> fields = {"username", "password", "emp_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("username", username);
    whereConditions.insert("password", password);

    QList<QVariantList> data;
    bool success = m_dbOperator->selectData("login", fields, whereConditions, data);

    if (!success) {
        QMessageBox::critical(this, "数据库错误", m_dbOperator->lastError());
        return false;
    }

    if (!data.isEmpty()) {
        // 存储用户角色
        m_userRole = (username.startsWith('a')) ? "admin" : "employee";
        
        // 从查询结果中获取员工ID
        // data的结构: [ [username, password, emp_id] ]
        if (data.size() > 0 && data[0].size() >= 3) {
            m_employeeId = data[0][2].toString();
        } else {
            QMessageBox::warning(this, "警告", "无法获取员工ID");
            return false;
        }
        
        return true;
    }

    return false;
}
